package com.yssoft.service.production;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.yssoft.common.Constants;
import com.yssoft.entity.production.TBatch;
import com.yssoft.entity.production.TLabelApply;
import com.yssoft.entity.production.TLabels;
import com.yssoft.entity.production.TMaterialRecord;
import com.yssoft.entity.production.TWorksheet;
import com.yssoft.entity.supplier.ProductCountCustom;
import com.yssoft.mapper.core.TDdDetailMapper;
import com.yssoft.mapper.production.TBatchMapper;
import com.yssoft.mapper.production.TLabelApplyMapper;
import com.yssoft.mapper.production.TLabelsMapper;
import com.yssoft.mapper.production.TMaterialRecordMapper;
import com.yssoft.mapper.production.TWorksheetMapper;
import com.yssoft.mapper.supplier.TProductCountMapper;
import com.yssoft.utils.AppUserHelper;
import com.yssoft.utils.LayuiUtil;
import com.yssoft.utils.MakeEncode;
import com.yssoft.utils.SessionUtil;
import com.yssoft.utils.UserHelper;

/**
 * @author 戈超
 * @time 2018/5/11 上午9:36
 */
@Service
public class WorkSheetService {
	private static Logger logger=Logger.getLogger(WorkSheetService.class);

	@Resource
	private TWorksheetMapper tWorksheetMapper;
	@Resource
    private TDdDetailMapper ddDetailMapper;
	@Resource
	private TMaterialRecordMapper tMaterialRecordMapper;
	@Resource
	private TLabelApplyMapper tLabelApplyMapper;
	@Resource
	private TLabelsMapper tLabelsMapper;
	@Resource
	private TBatchMapper tBatchMapper;

	/**
	 * 字典明细表一级查询
	 * @author 戈超
	 * @param request
	 * @return
	 */
	public List<Map<String, Object>> queryDdDetailOneList(String classify, HttpServletRequest request) {
		Map<String,Object> param = new HashMap<String, Object>();
		param.put("classify", classify);
		param.put("companyId", AppUserHelper.getCurrentCompanyId(request));
		List<Map<String, Object>> node = ddDetailMapper.queryListOneNode(param);
		return node;
	}

	/**
	 * 创建加工单
	 * @author 戈超
	 * @param tWorksheet
	 * @param materialId
	 * @param materialType
	 * @param quantity
	 * @param traceability_type
	 * @param request
	 * @return
	 */
	public int sheetSave(TWorksheet tWorksheet, Integer[] materialId, String[] materialType, String[] quantity,
			String traceability_type, HttpServletRequest request) {
		/*生成加工单号*/
		Map<String, Object> param = new HashMap<>();
		param.put("batchCode", "JG"+tWorksheet.getCode());
		param.put("tBId", tWorksheet.gettBId());
		Integer maxCode = tWorksheetMapper.queryCodeNum(param);
		String num = "00" + (++maxCode);
		num = num.substring(num.length() - 3, num.length());
		String code = "JG" + tWorksheet.getCode() + num;
		/*整理加工单数据*/
		tWorksheet.setCode(code);
		tWorksheet.setActualOutput("0");
		tWorksheet.setProcessStat("0");
		tWorksheet.setDeleteFlag("0");
		tWorksheet.setCreateTime(new Date());
		tWorksheet.setCreatorId(AppUserHelper.getCurrentUserId(request));
		tWorksheet.setCreatorName(AppUserHelper.getCurrentUserName(request));
		tWorksheet.setDeptId(AppUserHelper.getCurrentDeptId(request));
		tWorksheet.setDeptName(AppUserHelper.getCurrentDeptName(request));
		tWorksheet.settEId(AppUserHelper.getCurrentCompanyId(request));
		if(tWorksheet.getLinkPackage() == null){
			tWorksheet.setLinkPackage("0");
		}
		/*保存加工单*/
		int sheetSaveNum = tWorksheetMapper.insertSelective(tWorksheet);
		if(sheetSaveNum > 0){
			/*修改生产批次为已用*/
			TBatch tBatch = new TBatch();
			tBatch.setId(tWorksheet.gettBId());
			tBatch.setUseStat("1");
			tBatchMapper.updateByPrimaryKeySelective(tBatch);
			/*获取新增加工单id*/
			Integer id = tWorksheet.getId();
			/*保存物料使用数据*/
			if(materialId != null){
				for(int i = 0; i < materialId.length; i++){
					BigDecimal bd = new BigDecimal("0");
					if(quantity.length > 0 && quantity[i] != null && !"".equals(quantity[i])){
						bd=new BigDecimal(quantity[i]);
					}
					/*整理物料使用数据*/
					TMaterialRecord tMaterialRecord = new TMaterialRecord();
					tMaterialRecord.settWorksheeId(id);
					tMaterialRecord.setQuantity(bd);
					tMaterialRecord.settMId(materialId[i]);
					tMaterialRecord.setType(materialType[i]);
					tMaterialRecord.setDeleteFlag("0");
					tMaterialRecord.setCreateTime(tWorksheet.getCreateTime());
					tMaterialRecord.setCreatorId(tWorksheet.getCreatorId());
					tMaterialRecord.setCreatorName(tWorksheet.getCreatorName());
					tMaterialRecord.setDeptId(tWorksheet.getDeptId());
					tMaterialRecord.setDeptName(tWorksheet.getDeptName());
					tMaterialRecord.settEId(tWorksheet.gettEId());
					tMaterialRecordMapper.insertSelective(tMaterialRecord);
				}
			}

			if("2".equals(traceability_type)){
				String timeCode = Calendar.getInstance().getTimeInMillis() + "";
				BigDecimal tLabelApplyBd = new BigDecimal(0);
				/*追加保存标签申请数据*/
				TLabelApply tLabelApply = new TLabelApply();
				tLabelApply.setCode("SQ" + timeCode);
				tLabelApply.setQuantity(new BigDecimal(1));
				tLabelApply.setGrantQuantity(new BigDecimal(1));
				tLabelApply.setStat("1");
				tLabelApply.settBId(tWorksheet.gettBId());
				tLabelApply.setInvalidQuantity(tLabelApplyBd);
				tLabelApply.setRecallQuantity(tLabelApplyBd);
				tLabelApply.setFrozenQuantity(tLabelApplyBd);
				tLabelApply.setUsedQuantity(tLabelApplyBd);
				tLabelApply.setDeleteFlag("0");
				tLabelApply.setCreateTime(tWorksheet.getCreateTime());
				tLabelApply.setCreatorId(tWorksheet.getCreatorId());
				tLabelApply.setCreatorName(tWorksheet.getCreatorName());
				tLabelApply.setDeptId(tWorksheet.getDeptId());
				tLabelApply.setDeptName(tWorksheet.getDeptName());
				tLabelApply.settEId(tWorksheet.gettEId());
				tLabelApplyMapper.insertSelective(tLabelApply);
				Integer tLabelApplyId = tLabelApply.getId();
				/*追加保存标签数据*/
				TLabels tLabels = new TLabels();
				tLabels.setCode("LB" + timeCode);
				tLabels.setLabelStat("0");
				tLabels.setTraceType("2");
				tLabels.settLabelAppId(tLabelApplyId);
				tLabels.settWorksheeId(id);
				tLabels.setDeleteFlag("0");
				tLabels.setCreateTime(tWorksheet.getCreateTime());
				tLabels.setCreatorId(tWorksheet.getCreatorId());
				tLabels.setCreatorName(tWorksheet.getCreatorName());
				tLabels.setDeptId(tWorksheet.getDeptId());
				tLabels.setDeptName(tWorksheet.getDeptName());
				tLabels.settEId(tWorksheet.gettEId());

				String ip =request.getServerName();
				String basePath ="http://"+ip+":"+request.getServerPort()+request.getContextPath()+Constants.QRENCODE_SCAN_PATH;
				String url = MakeEncode.QREncode(basePath+tLabels.getCode());
				tLabels.setUrl(url);
				tLabels.setTurl(url);
				tLabelsMapper.insertSelective(tLabels);
			}
		}
		return sheetSaveNum;
	}

	/**
	 * 生产加工单修改回显
	 * @author 戈超
	 * @param wsId
	 * @return
	 */
	@Resource
	private TProductCountMapper productCountMapper;
	public Map<String, Object> querySheetById(Integer wsId) {
		/*获取加工单详细*/
		Map<String, Object> workSheet = tWorksheetMapper.selectWorksheetDetail(wsId);
		/*根据加工单获取物料使用数据*/
		List<Map<String, Object>> materials = tWorksheetMapper.queryMaterialRecord(wsId);
		/*根据产品查询是否有包材*/
		if(StringUtils.isNoneBlank(workSheet.get("pId")+"")) {
			Map<String, Object> param=new HashMap<>();
			param.put("productId", workSheet.get("pId"));
	    	List<ProductCountCustom>   materialList=productCountMapper.selectMaterialList(null,param);
	    	for (ProductCountCustom  material:materialList) {
				//类别（原料类别  rawClassify  包材 packagingClassify  添加剂 additiveClassify   辅料accessoriesClassify）
				String  classify=material.getClassify().toString();
				if( Constants.D_PACKAGING_CLASSIFY.equals( classify)   ) {
					workSheet.put("isPackagingClassify", true);
					break;
				}

			}
		}else {
			workSheet.put("isPackagingClassify", false);
		}
		/*将数据整合到一起*/
		//相关物料
		workSheet.put("materials", materials);
		return workSheet;
	}

	/**
	 * 生产加工单编辑
	 * @author 戈超
	 * @param tWorksheet
	 * @param materialId
	 * @param materialType
	 * @param quantity
	 * @param traceability_type
	 * @return
	 */
	public int sheetEdit(TWorksheet tWorksheet, Integer[] materialId, String[] materialType, String[] quantity,
			String traceability_type) {
		int result = tWorksheetMapper.updateByPrimaryKeySelective(tWorksheet);
		if(result > 0){
			if(materialId != null && materialId.length > 0){
				for(int i = 0; i < materialId.length; i++){
					BigDecimal bd = new BigDecimal("0");
					if(quantity.length > 0 && quantity[i] != null && !"".equals(quantity[i])){
						bd=new BigDecimal(quantity[i]);
					}
					TMaterialRecord tMaterialRecord = new TMaterialRecord();
					tMaterialRecord.setId(materialId[i]);
					tMaterialRecord.setQuantity(bd);
					tMaterialRecordMapper.updateByPrimaryKeySelective(tMaterialRecord);
				}
			}
		}
		return result;
	}

	/**
	 * 生产加工单删除
	 * @author 戈超
	 * @param id
	 * @return
	 */
	public int sheetDelete(Integer id) {
		TWorksheet tWorksheet = new TWorksheet();
		tWorksheet.setId(id);
		tWorksheet.setDeleteFlag("1");
		return tWorksheetMapper.updateByPrimaryKeySelective(tWorksheet);
	}

	public int complete(Integer id) {
		TWorksheet tWorksheet = new TWorksheet();
		tWorksheet.setId(id);
		tWorksheet.setProcessStat("2");
		return tWorksheetMapper.updateByPrimaryKeySelective(tWorksheet);
	}

	//根据生产批次id查询加工单
	public JSONObject findPageByTbId(int page, int limit, String tbId) {
		Integer teId =UserHelper.getCurrentCompanyId();//企业id
		PageHelper.startPage(page,limit);//下面第一个查询结果进行分页
        Map<String,Object> param=new HashMap<>();
        param.put("tbId", tbId);
        param.put("teId", teId);
        List<Map<String,Object>> list = tWorksheetMapper.selectAllSql(param);
        for (Map<String, Object> map : list) {
        	System.out.println(map.get("id"));
			 List<Map<String, Object>> labelList = tLabelsMapper.selectLabelListByWorkSheetId(Integer.valueOf(map.get("id").toString()));
			map.put("count", labelList.size());
		}
        int count = tWorksheetMapper.selectCountSql(param);//查询条数
        JSONObject jsonObject =LayuiUtil.getJSONObjectByMap(list,count,"","");
        return jsonObject;
	}
}
